/*
 * Copyright (c) OpenKoala 2011 All Rights Reserved
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.openkoala.koala.dd.ui;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.TreeItem;
import org.openkoala.koala.dd.event.DDTreeActionGroup;
import org.openkoala.koala.dd.event.SerializableUtil;
import org.openkoala.koala.dd.pojo.DDTree;
import org.openkoala.koala.dd.pojo.DDType;
import org.openkoala.koala.dd.pojo.StaticKeyValue;
import org.openkoala.koala.deploy.pojo.Itree;

/**
 * 类    名：DataDictionary.java
 *   
 * 功能描述：数据字典维护界面
 *  
 * 创建日期：2013-2-1上午8:56:48     
 * 
 * 版本信息：
 * 
 * 版权信息：Copyright (c) 2013 Koala All Rights Reserved
 * 
 * 作    者：lingen(lingen.liu@gmail.com)
 * 
 * 修改记录： 
 * 修 改 者    修改日期     文件版本   修改说明	
 */
public class DataDictionaryDialog extends Dialog {
    /**
     * 数据字典树
     */
    private TreeViewer treeViewer;

    /**
     * 静态下拉数据维护界面
     */
    private Composite staticDorpComposite;

    private Composite queryDropComposite;

    private TableViewer staticTableViewer;
    
    private Composite staticComposite;

    /**
     * @param parentShell
     */
    public DataDictionaryDialog(Shell parentShell) {
        super(parentShell);
    }

    protected void configureShell(Shell shell) {
        super.configureShell(shell);
        shell.setText("数据字典维护");
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        Composite composite = new Composite(parent, SWT.NONE);
        initializeDialogUnits(composite);
        GridData mainGridData = new GridData(700, 450);
        composite.setLayoutData(mainGridData);
        GridLayout gridLayout = new GridLayout();
        gridLayout.numColumns = 2;
        composite.setLayout(gridLayout);
        createTreeView(composite);
        createStaticDropView(composite);
        return parent;
    }

    /**
     * 创建左边的树节点
     * @param parent
     */
    private void createTreeView(final Composite parent) {
        GridData treeGridData = new GridData(GridData.FILL_VERTICAL);
        treeGridData.widthHint = 150;
        treeViewer = new TreeViewer(parent, SWT.BORDER | SWT.H_SCROLL);
        treeViewer.setLabelProvider(new DDTreeLabelProvider());
        treeViewer.setContentProvider(new DDTreeContentProvider());
        treeViewer.getTree().setLayoutData(treeGridData);
        java.util.List<Itree> trees = new ArrayList<Itree>();
        //初始化两个树节点
        Itree staticDrop = DDTree.getStaticDropDDTree();
        staticDrop.setChildren(queryDBStaticTrees());
        trees.add(staticDrop);
        
//        Itree queryDrop = DDTree.getQueryDropDDTree();
//        trees.add(queryDrop);
        treeViewer.setInput(trees);
        DDTreeActionGroup actionGroup = new DDTreeActionGroup(treeViewer);// 生成一个ActionGroup对象
        actionGroup.fillContextMenu(new MenuManager());// 将按钮注入到菜单对象中
        treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
            @Override
            public void selectionChanged(SelectionChangedEvent event) {
                TreeItem items[] = treeViewer.getTree().getSelection();
                if (items.length > 0) {
                	DDTree tree = (DDTree) items[0].getData();
                    if (tree.getType().equals(DDType.staticDropDown) || tree.getType().equals(DDType.queryDropDown)){
                        staticComposite.setVisible(false);
                    }
                    else{
                        staticComposite.setVisible(true);
                        staticTableViewer.setInput(tree.getValues());
                    }
                }
            }
        });
    }

    private void createStaticDropView(Composite parent) {
        GridData gridData = new GridData(GridData.FILL_VERTICAL);
        gridData.widthHint = 600;
        
        staticComposite = new Composite(parent,SWT.None);
        staticComposite.setLayoutData(gridData);
        staticComposite.setLayout(new FormLayout());
        
        //创建一个TABLE
        staticTableViewer = new TableViewer(staticComposite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION
                | SWT.BORDER);
        createColumns(staticComposite);
        // Make lines and make header visible
        final Table table = staticTableViewer.getTable();
        table.setHeaderVisible(true);
        table.setLinesVisible(true);
        
        staticTableViewer.setContentProvider(ArrayContentProvider.getInstance());
        staticTableViewer.setInput(new ArrayList<StaticKeyValue>());
        //staticTableViewer.getTable().setLayoutData(gridData);
        FormData data = new FormData();
        data.top = new FormAttachment(0,5);
        data.left = new FormAttachment(0,5);
        data.right = new FormAttachment(staticTableViewer.getTable(),380,SWT.LEFT);
        data.bottom = new FormAttachment(99,3);
        staticTableViewer.getTable().setLayoutData(data);
        
        Button addButton = new Button(staticComposite,SWT.PUSH);
        addButton.setText("新增属性");
        data = new FormData();
        data.top = new FormAttachment(0,30);
        data.left = new FormAttachment(staticTableViewer.getTable(),5);
        data.right = new FormAttachment(addButton,100,SWT.LEFT);
        data.bottom = new FormAttachment(addButton,25,SWT.TOP);
        addButton.setLayoutData(data);
        addButton.addSelectionListener(new SelectionListener(){

            @Override
            public void widgetSelected(SelectionEvent e) {
                KeyValueDialog dialog = KeyValueDialog.getInstance();
                dialog.open();
                if(dialog.getReturnCode()==0){
                    String key = dialog.getKey();
                    String value = dialog.getValue();
                    StaticKeyValue keyValue = new StaticKeyValue(key,value);
                    List<StaticKeyValue> inputs = (List<StaticKeyValue>)staticTableViewer.getInput();
                    inputs.add(keyValue);
                    staticTableViewer.refresh();
                    
                }
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
                
            }});
        
        Button mofidyButton = new Button(staticComposite,SWT.PUSH);
        mofidyButton.setText("修改属性");
        data = new FormData();
        data.top = new FormAttachment(addButton,10);
        data.left = new FormAttachment(staticTableViewer.getTable(),5);
        data.right = new FormAttachment(mofidyButton,100,SWT.LEFT);
        data.bottom = new FormAttachment(mofidyButton,25,SWT.TOP);
        mofidyButton.setLayoutData(data);
        mofidyButton.addSelectionListener(new SelectionListener(){

            @Override
            public void widgetSelected(SelectionEvent e) {
                TableItem[] items = staticTableViewer.getTable().getSelection();
                if(items!=null && items.length>0){
                    StaticKeyValue value = (StaticKeyValue)items[0].getData();
                    KeyValueDialog dialog = KeyValueDialog.getInstance();
                    dialog.refersh(value.getKey(), value.getValue());
                    dialog.open();
                    if(dialog.getReturnCode()==0){
                        value.setKey(dialog.getKey());
                        value.setValue(dialog.getValue());
                        staticTableViewer.refresh();
                    }
                }
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
                
            }});
        
        Button removeButton = new Button(staticComposite,SWT.PUSH);
        removeButton.setText("删除属性");
        data = new FormData();
        data.top = new FormAttachment(mofidyButton,5);
        data.left = new FormAttachment(staticTableViewer.getTable(),5);
        data.right = new FormAttachment(removeButton,100,SWT.LEFT);
        data.bottom = new FormAttachment(removeButton,25,SWT.TOP);
        removeButton.setLayoutData(data);
        
          removeButton.addSelectionListener(new SelectionListener(){

            @Override
            public void widgetSelected(SelectionEvent e) {
                
                TableItem[] items = staticTableViewer.getTable().getSelection();
                if(items!=null && items.length>0){
                    
                    TreeItem[] trees = treeViewer.getTree().getSelection();
                    DDTree tree = (DDTree)(trees[0].getData());
                    
                    for(TableItem item:items){
                        StaticKeyValue value = (StaticKeyValue)item.getData();
                        List<StaticKeyValue> inputs = (List<StaticKeyValue>)staticTableViewer.getInput();
                        inputs.remove(value);
                    }
                    staticTableViewer.refresh();
                    
                }
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
                
            }});
        staticComposite.setVisible(false);
    }

    /**
     * @param parent
     */
    private void createColumns(Composite parent) {
        
        TableViewerColumn key = new TableViewerColumn(staticTableViewer, SWT.NONE);
        key.getColumn().setWidth(180);
        key.getColumn().setText("KEY值:");
        key.setLabelProvider(new ColumnLabelProvider() {
          @Override
          public String getText(Object element) {
            StaticKeyValue value = (StaticKeyValue) element;
            return value.getKey();
          }
        });
        
        TableViewerColumn value = new TableViewerColumn(staticTableViewer, SWT.NONE);
        value.getColumn().setWidth(180);
        value.getColumn().setText("VALUE值:");
        value.setLabelProvider(new ColumnLabelProvider() {
          @Override
          public String getText(Object element) {
            StaticKeyValue value = (StaticKeyValue) element;
            return value.getValue();
          }
        });
    }

    @Override
    protected void okPressed() {
        List<DDTree> trees = (List<DDTree>) treeViewer.getInput();
        for(DDTree tree:trees){
            if(tree.getType().equals(DDType.staticDropDown)){
                List<DDTree> childs = tree.getChildren();
                SerializableUtil.serializableStaticDict(childs);
            }
        }
        super.okPressed();
    }
    
    public List<DDTree> queryDBStaticTrees(){
        return SerializableUtil.getStaticDictFromSerializable();
    }
    
}
